<template>
  <div class="attr-list">
    <CommonAttr></CommonAttr>
    <el-form>
      <el-form-item label="对齐方式">
        <el-select v-model="imgPropValue.fit" placeholder="请选择" @change="handChange">
          <el-option v-for="(item, index) in imageFitOptions" :key="index" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <!-- 上传图片 -->
    <label for="edit" class="insert">
      修改图片
      <input id="edit" type="file" hidden @change="edltImg" />
    </label>
  </div>
</template>

<script>
import CommonAttr from '@/components/Attribute/CommonAttr.vue'
import { imageFitOptions } from '@/components/Attribute/Attr.js'
import { mapState } from 'vuex'
import { cutStyle } from '@/utils/style.js'

export default {
  data() {
    return {
      imageFitOptions,
      filelist: []
    }
  },
  computed: {
    ...mapState(['curComponent']),
    imgPropValue() {
      return this.curComponent.propValue
    },
    imgStyle() {
      return this.curComponent.style
    }
  },
  components: {
    CommonAttr
  },
  methods: {
    handChange() {
      this.$store.commit('editorPropValue', this.imgPropValue)
    },
    // 上传成功时修改图片
    edltImg(e) {
      const file = e.target.files[0]
      if (!file.type.includes('image')) {
        return this.$message.error('只能上传图片！')
      }
      const reader = new FileReader()
      reader.onload = (res) => {
        const fileResult = res.target.result
        const img = new Image()
        img.src = fileResult

        img.onload = () => {
          this.imgPropValue.src = fileResult
          // 修改图片
          this.handChange(this.imgPropValue)

          // 等比例缩放
          let curImgStyle = cutStyle(this.imgStyle)
          const newWidth = Math.ceil(curImgStyle.height * (img.width / img.height))
          this.imgStyle.width = `${newWidth}px`
          this.$store.commit('setCurComponentStyle', this.imgStyle)
        }
      }
      reader.readAsDataURL(file)
    }
  }
}
</script>

<style lang="less" scoped>
.insert {
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  text-align: center;
  box-sizing: border-box;
  outline: 0;
  margin: 0;
  transition: 0.1s;
  font-weight: 500;
  padding: 9px 15px;
  font-size: 12px;
  border-radius: 3px;

  &:active {
    color: #3a8ee6;
    border-color: #3a8ee6;
    outline: 0;
  }

  &:hover {
    background-color: #ecf5ff;
    color: #3a8ee6;
  }
}
</style>
